package com.szgz.platform.callback;

import com.github.dockerjava.api.model.WaitResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DockerResultCallback implements com.github.dockerjava.api.async.ResultCallback<WaitResponse> {

    private WaitResponse waitResponse;
    private final CountDownLatch latch = new CountDownLatch(1);
    private Throwable error;

    @Override
    public void onStart(Closeable closeable) {
        log.info("DockerResultCallback onStart======>:{}", closeable);
    }

    @Override
    public void onNext(WaitResponse waitResponse) {
        log.info("DockerResultCallback onNext======>:{}", waitResponse);
        this.waitResponse = waitResponse;
    }

    @Override
    public void onError(Throwable throwable) {
        log.error("DockerResultCallback onError======>:{}", throwable.getMessage());
        this.error = throwable;
        latch.countDown();
    }

    @Override
    public void onComplete() {
        log.info("DockerResultCallback onComplete======>");
        latch.countDown();
    }

    @Override
    public void close() throws IOException {
        log.info("DockerResultCallback close======>");
        latch.countDown();
    }

    public WaitResponse getWaitResponse() {
        return waitResponse;
    }

    public void awaitCompletion() throws InterruptedException {
        latch.await();
    }

    public void awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {
        latch.await(timeout, unit);
    }

    public Throwable getError() {
        return error;
    }
}